const app = getApp();

Page({
  data: {
    isLoggedIn: false,  // 登录状态
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  },

  onLoad() {
    wx.setNavigationBarTitle({
      title: '修改密码'
    });
    this.checkLoginStatus();
  },

  onShow() {
    this.checkLoginStatus();
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    const isLoggedIn = !!(token && riderId);
    this.setData({ isLoggedIn });

    if (!isLoggedIn) {
      // 未登录时清空输入数据
      this.setData({
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      });
    }
  },

  // 跳转到登录页面
  goToLogin() {
    wx.navigateTo({
      url: '/pages/logs/logs'
    });
  },

  // 输入旧密码
  onOldPasswordInput(e) {
    this.setData({
      oldPassword: e.detail.value
    });
  },

  // 输入新密码
  onNewPasswordInput(e) {
    this.setData({
      newPassword: e.detail.value
    });
  },

  // 确认新密码
  onConfirmPasswordInput(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },

  // 提交修改密码
  onSubmit() {
    const { oldPassword, newPassword, confirmPassword } = this.data;

    // 验证输入
    if (!oldPassword) {
      wx.showToast({ title: '请输入原密码', icon: 'none' });
      return;
    }

    if (!newPassword) {
      wx.showToast({ title: '请输入新密码', icon: 'none' });
      return;
    }

    if (newPassword.length < 6) {
      wx.showToast({ title: '新密码至少6位', icon: 'none' });
      return;
    }

    if (newPassword !== confirmPassword) {
      wx.showToast({ title: '两次密码输入不一致', icon: 'none' });
      return;
    }

    if (oldPassword === newPassword) {
      wx.showToast({ title: '新密码不能与原密码相同', icon: 'none' });
      return;
    }

    this.changePassword();
  },

  // 验证原密码
  checkOldPassword() {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    return new Promise((resolve, reject) => {
      wx.request({
        url: `${ip}/api/riders/checkPassword`,
        method: 'POST',
        header: {
          'Authorization': 'Bearer ' + token,
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: {
          id: riderId,
          password: this.data.oldPassword
        },
        success: (res) => {
          if (res.data.code === 200) {
            resolve(res.data.data); // 返回布尔值
          } else {
            reject(res.data.message || '密码验证失败');
          }
        },
        fail: () => {
          reject('网络请求失败');
        }
      });
    });
  },

  // 调用修改密码API
  async changePassword() {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    if (!token || !riderId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '验证原密码...' });

    try {
      // 先验证原密码
      const isOldPasswordValid = await this.checkOldPassword();

      if (!isOldPasswordValid) {
        wx.hideLoading();
        wx.showToast({ title: '原密码错误', icon: 'none' });
        return;
      }

      // 原密码正确，继续修改密码
      wx.showLoading({ title: '修改密码中...' });

      wx.request({
        url: `${ip}/api/riders/update`,
        method: 'POST',
        header: {
          'Authorization': 'Bearer ' + token,
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: {
          id: riderId,
          password: this.data.newPassword,
          // 这里需要传递其他必要字段，从全局数据或缓存中获取
          name: wx.getStorageSync('riderName') || '',
          phone: wx.getStorageSync('riderPhone') || '',
          vehicleType: wx.getStorageSync('riderVehicleType') || 1,
          vehiclePlate: wx.getStorageSync('riderVehiclePlate') || '',
          status: wx.getStorageSync('riderStatus') || 1
        },
        success: (res) => {
          wx.hideLoading();
          if (res.data.code === 200) {
            wx.showToast({
              title: '密码修改成功',
              icon: 'success',
              duration: 2000
            });

            // 清空输入框
            this.setData({
              oldPassword: '',
              newPassword: '',
              confirmPassword: ''
            });

            // 延迟返回上一页
            setTimeout(() => {
              wx.navigateBack();
            }, 2000);
          } else {
            wx.showToast({
              title: res.data.message || '修改失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          wx.hideLoading();
          wx.showToast({ title: '网络请求失败', icon: 'none' });
        }
      });

    } catch (error) {
      wx.hideLoading();
      wx.showToast({ title: error, icon: 'none' });
    }
  },

  // 返回上一页
  onBack() {
    wx.navigateBack();
  }
});
